import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver } from '@angular/core';
import * as _ from "lodash";
import { FlowInfoComponent } from '../../modal/flow-info/flow-info.component';
import { DataInTransitPageService } from './data-in-transit-page.service';
import { DataService } from 'app/services/data.service';
import { Util } from '../../../../../common/util';
import { TablePageComponent } from '../../modal/table/table-page/table-page.component';

@Component({
  selector: 'app-data-in-transit-page',
  templateUrl: './data-in-transit-page.component.html',
  styleUrls: ['./data-in-transit-page.component.scss'],
  providers: [DataInTransitPageService]
})
export class DataInTransitPageComponent implements OnInit {

  //在途数据列表
  @ViewChild("transitTablePage", { read: ViewContainerRef })
  transitTablePage: ViewContainerRef;
  tablePageComponent: ComponentRef<TablePageComponent>;
  @ViewChild("flowInfo", { read: ViewContainerRef })
  flowInfo: ViewContainerRef;
  flowInfoComponent: ComponentRef<FlowInfoComponent>;
  // lodash
  public _: any = _;

  public cloneList: any = [];
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 适用基金组数据
  public fundGroup: any;
  // 字典值
  public dictionaryList: any;
  // 列表数据
  public listData: any = [];
  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //列表全选
  public isCheckedAll: any = false;

  //查询列表getBody
  public getBody: any = {
    pageIndex: '',
    pageSize: '',
    sOprDateStart: '',//发起日期起始区间
    sOprDateEnd: '',//发起日期结束区间
    sFileName: '',// 文件名称
    nBatchNoStart: '',//批次号起始区间
    nBatchNoEnd: '',// 批次号结束区间
    sFundType: '',
    sFundGroupds: '',
    commitOprZh: '',
    sAccountName: '',
    f1: '',
    sValid: ''
  };
  public sFundGroupds: any = [];
  constructor(public resolver: ComponentFactoryResolver,
    public dataInTransitService: DataInTransitPageService,
    public dataService: DataService,
  ) { }

  ngOnInit() {
    let that = this;
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    // 多选下拉框
    window['$'](".select2").select2();
    this.fundGroupBaseList();
    this.loadlist();
    // setTimeout(() => {
    //   this.fundGroupsSelect2();
    // }, 500)
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        // let SessionMenuData = sessionStorage.getItem('menu');
        // this.menuData = JSON.parse(SessionMenuData)
        // this.menuResourceSet = [];
        // _.forEach(this.menuData, (item, index) => {
        //   if (item.sName == '风控管理') {
        //     _.forEach(item.children, (it, idx) => {
        //       if (it.sName == '非QDII条目管理') {
        //         _.forEach(it.children, (ite, i) => {
        //           if (ite.sName == '在途数据') {
        //             that.menuResourceSet = ite.resourceSet
        //             sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
        //           }
        //         })
        //       }
        //     })
        //   }
        // })
        this.menuResourceSet = [];
        this.menuResourceSet = Util.getAuthority('风控管理', '非QDII条目管理', '在途数据');
        sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
      }
    })
    this.menuResourceSet = [];
    this.menuResourceSet = Util.getAuthority('风控管理', '非QDII条目管理', '在途数据');
    sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
    console.info(this.menuResourceSet)
  }

  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.loadlist();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.loadlist(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }

  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  //分页列表
  loadlist(pageNum?, pageSize?) {
    let that = this;
    // let salesChecked = [];
    // let salesIdList;
    // let selected = window['$']('.fields-select').val();
    // console.log(selected);
    // this.getListBody.sFundGroupds = selected;
    // _.forEach(selected, item => {
    //   console.log(item);
    //   // let index1 = item.indexOf("'");
    //   // let index2 = item.lastIndexOf("'");  
    //   // let sales = item.substring(index1 + 1, index2);
    //   salesChecked.push(item);
    // })
    // salesIdList = salesChecked.join(",");
    this.getBody.sFundGroupds = this.sFundGroupds.join(',');
    this.isCheckedAll = false;
    Util.trimPostItem(this.getBody);
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.dataInTransitService.list(this.getBody).subscribe(data => {
      if (data) {
        this.listData = data.list;
        this.listPageInfo.currentPageNum = data.pageNum;
        this.listPageInfo.totalPages = data.pages;
        this.listPageInfo.total = data.total;
        this.listPageInfo.startRow = data.startRow;
        this.listPageInfo.endRow = data.endRow;
        this.cloneList = _.cloneDeep(data.list);
        this.controlDom();
        this.showTablePage(this.listData)
      }
    })
  }

  // 显示modal
  showModal() {
    let that = this;
    let checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        checkProduct.push(item);
      }
    });
    if (checkProduct.length == 1) {
      if (this.flowInfoComponent && this.flowInfoComponent.instance) {
        this.flowInfoComponent.destroy();
      }
      // 动态创建组件的实例
      const flowInfoComponent = this.resolver.resolveComponentFactory(FlowInfoComponent);
      this.flowInfoComponent = this.flowInfo.createComponent(flowInfoComponent);
      this.flowInfoComponent.instance.item = checkProduct[0];
      window['$']('#modal1').modal('show');

    } else {
      window["swal"]("提示", "请选择一条记录！", "warning");
    }
  }

  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 获取适用基金组
  fundGroupBaseList() {
    let getbody = {
      sType: 0,//非QDII传0
    }
    this.dataInTransitService.fundGroupList(getbody).subscribe((data) => {
      this.fundGroup = data
      console.info(this.fundGroup)
      let that = this;
      var html = '';
      for (var i = 0; i < this.fundGroup.length; i++) {
        html += "<option value='" + this.fundGroup[i].nFgId + "'>" + this.fundGroup[i].sFgName + "</option>";
      }
      window['$']("#NqdiiDITFundGroupds").html(html);
      window['$']('#NqdiiDITFundGroupds').selectpicker({
        size: "8",
        actionsBox: "true",
        title: "请选择",
        selectAllText: "全选",
        deselectAllText: "取消全选",
        width: 150
      });
    })
  }
  //初始化适用基金组多选框
  // fundGroupsSelect2() {
  //   let that = this;
  //   var html = '';
  //   for (var i = 0; i < this.fundGroup.length; i++) {
  //     html += "<option value='" + this.fundGroup[i].nFgId + "'>" + this.fundGroup[i].sFgName + "</option>";
  //   }
  //   window['$']("#NqdiiDITFundGroupds").html(html);
  //   window['$']('#NqdiiDITFundGroupds').selectpicker({
  //     size: "8",
  //     actionsBox: "true",
  //     title: "请选择",
  //     selectAllText: "全选",
  //     deselectAllText: "取消全选",
  //     width: 150
  //   });
  // }
  //搜索查询
  searchQuery() {
    let that = this;
    if (Util.dateOrder(that.getBody.sOprDateStart, that.getBody.sOprDateEnd)) {
      if (that.getBody.nBatchNoEnd != '' && that.getBody.nBatchNoStart != '') {
        if (parseInt(that.getBody.nBatchNoEnd) > parseInt(that.getBody.nBatchNoStart)) {
          that.loadlist();
        } else {
          window['swal']("提示", "起始批次 须小于 结束批次", "warning");
        }
      } else {
        that.loadlist();
      }
    } else {
      window['swal']("提示", "发行日期 须早于 到期日期", "warning");
    }
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.listData, [colName], ["asc"]);
    if (JSON.stringify(this.listData) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.listData, [colName], ["desc"]);
    }
    this.listData = listDataAsc;
  }
  //根据编号是否相同操控dom
  controlDom() {
    let that = this;
      if (this.listData != undefined) {
        for (let i = 0; i < this.listData.length - 1; i++) {
          if (that.listData[i].nNjId == that.listData[i + 1].nNjId) {
            // window['$']('#routeCheck' + i).remove();
            _.forIn(that.listData[i], (item1, key1) => {
              let index1 = i + 1;
              let index2 = i + 2;
              let id1 = "#data-table table tbody tr:nth-child(" + index1 + ") td div[name=" + key1 + "]";
              let id2 = "#data-table table tbody tr:nth-child(" + index2 + ") td div[name=" + key1 + "]";
              if (item1 == that.listData[i + 1][key1]) {
                // window['$'](id1).removeClass('font-color');
                // window['$'](id2).removeClass('font-color');
              } else {
                that.cloneList[i + 1][key1] = 'red';
              }
            })
          }
        }
      }
  }

  //在途数据列表
  showTablePage(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.tablePageComponent && this.tablePageComponent.instance) {
      this.tablePageComponent.destroy();
    }

    // 动态创建组件的实例
    const tablePageComponent = this.resolver.resolveComponentFactory(TablePageComponent);
    this.tablePageComponent = this.transitTablePage.createComponent(tablePageComponent);
    this.tablePageComponent.instance.listData = item;
    this.tablePageComponent.instance.listType = '6';
    this.tablePageComponent.instance.setColor = this.cloneList;
  }
}
